package com.corn.juc.pool;

import jdk.nashorn.internal.ir.ReturnNode;

import java.sql.Time;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/1/4 11:13
 */

public class CallableDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        futureTaskDemo();
        completableFutureTest();
    }

    /**
     * 使用jdk8 的completableFuture编排
     *
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void completableFutureTest() throws InterruptedException, ExecutionException {
        CompletableFuture<Void> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        })
                .thenApply(i -> i * 200)
                .thenAccept(System.out::println);
        completableFuture.get();
    }

    /**
     * 使用callable
     *
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void futureTaskDemo() throws InterruptedException, ExecutionException {
        // 方式一:
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(2);
            return 100;
        });
        futureTask.run();
        System.out.println(futureTask.get());

        // 方式二:
        FutureTask<Integer> futureTask2 = new FutureTask<>(() -> {
            TimeUnit.SECONDS.sleep(2);
            return 200;
        });
        Thread t2 = new Thread(futureTask2);
        t2.start();
        System.out.println(futureTask2.get());
    }
}
